<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

class News extends CI_Controller
{
    protected $sesja= null;
    protected $log  = null;
    protected $elems= null;
    
    public function __construct() 
    {
        parent::__construct();
        $this->load->model('News_model','news');
        $this->sesja= $this->session->userdata('sesja');
        $this->log  = new Logevent();
        $this->elems= new Elements();
    }
    
    public function list_news() 
    {
        $head['h1'] = 'Najświeższe wiadomości';
        $view       = 'news/show_news';
        $content    = $this->news->get_all_news();
        $this->elems->load_view($this->sesja,$view,$content,$head);
    }
    
    public function read($id) 
    {
        if(is_numeric($id))
        {
            $news = $this->news->get_news($id);
            if($news['stan'])
            {
                $head['h1']     = $news['wynik']['title'];
                $head['stitle'] = $news['wynik']['seo']['title'];
                $head['sdesc']  = $news['wynik']['seo']['desc'];
                $head['skeys']  = $news['wynik']['seo']['keys'];
                $cont['news']   = $news['wynik'];
                $this->elems->load_view($this->sesja,'news/show_article',$cont,$head);
            }
            else
                $this->elems->load_alert($this->sesja,'error','Nie ma takiego newsa!.');
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie ma takiego newsa.');
    }
    
    public function add_news() 
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            $head['h1']     = 'Dodaj nowy artykuł';
            $foot['js']     = array(
                'ckeditor/ckeditor.js',
                'js/default/ckeditor.config.js',
                'js/default/datepicker.js'
            );
            $view           = 'news/add_news';
            $content        = '';
            $content['cats']= $this->news->get_categories();
            $content['tags']= $this->news->get_tags();
            $this->elems->load_view($this->sesja,$view,$content,$head,$foot);
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function edit_news($news) {}
    
    public function insert_news() 
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1 && $_POST['add_news'])
        {
            $this->load->library('form_validation');
            //mpr($_POST,1);
            $this->form_validation->set_error_delimiters('<p class="error">','</p>');
            $this->form_validation->set_rules('title','Tytuł artykułu','required|xss_clean');
            $this->form_validation->set_rules('kategoria','Kategoria','required|xss_clean');
            $this->form_validation->set_rules('intro','Wstęp/intro artykułu','required|xss_clean');
            $this->form_validation->set_rules('content','Część główna','required|xss_clean');
            $this->form_validation->set_rules('data_publ','Data publikacji','required|xss_clean');
            $this->form_validation->set_rules('published','Opublikowany?','xss_clean');
            $this->form_validation->set_rules('seo-title','Tytuł SEO','xss_clean');
            $this->form_validation->set_rules('seo-desc','Treść SEO','xss_clean');
            $this->form_validation->set_rules('seo-keys','Słowa kluczowe SEO','xss_clean');
            
            if($this->form_validation->run() == FALSE && isset($_POST['add_news']))
                $this->add_news();
            elseif($this->form_validation->run() == FALSE && isset($_POST['edit_news']))
                $this->edit_news($this->input->post('nid'));
            else
            {
                $time = date('G:i');
                $data = $this->input->post('data_publ');
                $publ = new DateTime($data.' '.$time);
                $news['news_title']     = $this->input->post('title');
                $news['news_slug']      = remove_pl($this->input->post('title')); 
                $news['news_date']      = $publ->format('U');
                $news['news_author']    = $this->sesja['id'];
                $news['news_intro']     = $this->input->post('intro');
                $news['news_text']      = $this->input->post('content');
                $news['news_published'] = $this->input->post('published');
                $news['news_image']     = get_image_from_txt($this->input->post('content'));
                $news['news_seotitle']  = $this->input->post('seo-title');
                $news['news_seodesc']   = $this->input->post('seo-desc');
                $news['news_seokeys']   = $this->input->post('seo-keys');
                $newscat['nc_cat']   = $this->input->post('kategoria');
                //mpr($news);
                $tab = $this->news->insert_news($news,$newscat);
                if($tab['stan'])
                    $this->elems->load_alert($this->sesja,'success','Dodano artykuł do bazy danych',anchor('news/read/'.$tab['nc_news'].'/'.$news['news_slug']));
                else
                    $this->elems->load_alert($this->sesja,'error','Wystąpił błąd podczas dodawania artykułu do bazy danych<br/>MySQL: '.$this->db->last_query());
            }
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function remove_news($news) {}
    
    public function list_categories() 
    {
        if(isset($this->sesja) && $this->sesja['editor']==1)
        {
            $cats = $this->news->get_categories();
            if($cats['stan'])
            {
                $head['h1'] = 'Lista kategorii';
                $cont['cats'] = $cats['cats'];
                $foot['js'] = array(
                    'js/libs/jquery.ui.nestedSortable.js',
                    'js/news/show_categories.js'
                );
                $this->elems->load_view($this->sesja,'news/show_categories',$cont,$head,$foot);
            }
            else
                $this->elems->load_alert($this->sesja,'alert','Brak dostępnych kategorii',anchor('news/add_category','Dodaj kategorię do systemu',array('class'=>'btn btn_primary')));
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function add_category()
    {
        if(isset($this->sesja) && $this->sesja['editor']==1)
        {
            $cats = $this->news->get_categories(FALSE);
            $head['h1'] = 'Dodaj kategorię';
            $cont['cats'] = $cats['cats'];            
            $cont['cats'][0]['name'] = '----------------------------------------------';
            $this->elems->load_view($this->sesja,'news/add_category',$cont,$head);
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function edit_category($cid) { }
    
    public function update_category_order()
    {
        if(isset($this->sesja) && $this->sesja['editor']==1)
        {
            $wynik = $this->input->post('list');
            $wynik = json_decode($wynik);
            if($this->news->update_order($wynik))
                return TRUE;
            else
                return FALSE;
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function insert_category() 
    {
        if(isset($this->sesja) && $this->sesja['editor']==1 && ($this->input->post('add_category') || $this->input->post('add_category')))
        {
            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<p class="error">','</p>');
            $this->form_validation->set_rules('name','Nazwa kategorii','required|xss_clean');
            $this->form_validation->set_rules('parent','Kategoria nadrzędna','integer|required|xss_clean');
            if($this->form_validation->run() == FALSE && $this->input->post('add_category'))
                $this->add_category();
            elseif($this->form_validation->run() == FALSE && $this->input->post('edit_category'))
                $this->edit_category($this->input->post('nid'));
            else
            {
                $tab['cat_name']    = $this->input->post('name');
                $tab['cat_parent']  = $this->input->post('parent');
                if($stan = $this->news->insert_category($tab))
                {
                    $this->log->log_event($this->sesja,$stan);
                    $this->elems->load_alert(
                        $this->sesja,
                        'success',
                        'Dodano kategorię do bazy danych',
                        anchor(
                            'news/add_category',
                            'Dodaj następną kategorię',
                            array('class'=>'btn btn-primary btn-large')
                        )
                    );
                }
                else
                    $this->elems->load_alert($this->sesja,'error','Nie udało się dodać kategorii do systemu',get_back_link());
            }
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function remove_category($cat) {}
    
    public function list_news_by_category($cat) {}
    
    public function upload_image()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1 && isset($_GET['CKEditor']))
        {
            if(!file_exists('./upload/news/'.date('Y-m-d')))
                mkdir('./upload/news/'.date('Y-m-d'),0777);
            $upload['upload_path']  = './upload/news/'.date('Y-m-d');
            $upload['allowed_types']= 'gif|jpg|png';
            $upload['max_size']     = '512';
            $upload['file_name']    = 'news-'.date('Y-m-d').'-'.do_hash($_FILES['upload']['name']);
            $this->load->library('upload',$upload);

            $message= '';
            if(!$this->upload->do_upload('upload'))
                $message = $this->upload->display_errors();
            else
            {
                $data = $this->upload->data();
                $obraz= $data['file_name'];
            }
            $url = $upload['upload_path'].$obraz;
            $funcNum = $_GET['CKEditorFuncNum'];
            echo '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$funcNum.','.$url.','.$message.');</script>';
        }
        else
            echo 'Nie masz uprawnień do korzystania z tej strony';
    }
    
    public function browse_images()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1 && isset($_GET['CKEditor']))
        {
            $images = glob('./upload/news/'.date('Y-m-d').'/{*.jpg,*.png,*.gif}',GLOB_BRACE);
            shuffle($images);
            echo '<ul>';
            foreach($images as $image)
                echo '<li><img alt="" src="'.base_url().$image.'" style="width: 100px; height: auto;"/></li>';
            echo '</ul>';
        }
        else
            echo 'Nie masz uprawnień do korzystania z tej strony';
    }

}